<template>
  <div class="my-orders-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>我的订单</h1>
        <p>共 {{ totalOrdersCount }} 个订单</p>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          @click="loadOrders"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="状态">
          <el-select
            v-model="filters.status"
            placeholder="全部状态"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="confirmed" />
            <el-option label="使用中" value="using" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="日期">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="filters.search"
            placeholder="搜索订单号、台球桌..."
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单表格 -->
    <div class="orders-table-container">
      <!-- 批量操作栏 -->
      <div v-if="selectedOrders.length > 0" class="batch-actions">
        <span class="batch-info">已选择 {{ selectedOrders.length }} 个订单</span>
        <div class="batch-buttons">
          <el-button size="small" @click="batchPayOrders" :disabled="!canBatchPay">
            批量支付
          </el-button>
          <el-button size="small" type="danger" @click="batchCancelSelected" :disabled="!canBatchCancel">
            批量取消
          </el-button>
          <el-button size="small" link @click="clearSelection">清空选择</el-button>
        </div>
      </div>

      <!-- 订单表格 -->
      <el-table
        :data="filteredOrders"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
        class="orders-table"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="订单号" width="180">
          <template #default="{ row }">
            <span class="order-id">{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="tableName" label="台球桌" width="120">
          <template #default="{ row }">
            <div class="table-info">
              <div class="table-name">{{ row.tableName }}</div>
              <div class="table-type">{{ row.tableType }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="开始时间" width="140">
          <template #default="{ row }">
            <div class="time-info">
              <div class="date">{{ formatDate(row.date) }}</div>
              <div class="time">{{ row.startTime }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="结束时间" width="140">
          <template #default="{ row }">
            <div class="time-info">
              <div class="date">{{ formatDate(row.date) }}</div>
              <div class="time">{{ row.endTime }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="duration" label="时长(小时)" width="100" align="center">
          <template #default="{ row }">
            <span class="duration">{{ row.duration }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="totalCost" label="金额" width="100" align="center">
          <template #default="{ row }">
            <span class="cost">¥{{ row.totalCost }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="row.status === 'pending'"
                type="success"
                size="small"
                @click="payOrder(row)"
              >
                支付
              </el-button>
              <el-button
                v-if="row.status === 'confirmed'"
                type="primary"
                size="small"
                @click="startUsing(row)"
              >
                开始
              </el-button>
              <el-button
                v-if="row.status === 'using'"
                type="warning"
                size="small"
                @click="finishUsing(row)"
              >
                结束
              </el-button>
              <el-button
                v-if="['pending', 'confirmed'].includes(row.status)"
                type="danger"
                size="small"
                @click="cancelOrderLocal(row)"
              >
                取消
              </el-button>
              <el-button
                size="small"
                @click="viewOrderDetail(row)"
              >
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadOrders"
          @current-change="loadOrders"
        />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="500px"
    >
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">订单号:</span>
              <span class="value">{{ selectedOrder.id }}</span>
            </div>
            <div class="detail-item">
              <span class="label">台球桌:</span>
              <span class="value">{{ selectedOrder.tableName }} ({{ selectedOrder.tableType }})</span>
            </div>
            <div class="detail-item">
              <span class="label">状态:</span>
              <el-tag :type="getStatusType(selectedOrder.status)">{{ getStatusText(selectedOrder.status) }}</el-tag>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>预订信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">预订日期:</span>
              <span class="value">{{ selectedOrder.date }}</span>
            </div>
            <div class="detail-item">
              <span class="label">开始时间:</span>
              <span class="value">{{ selectedOrder.startTime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">结束时间:</span>
              <span class="value">{{ selectedOrder.endTime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">使用时长:</span>
              <span class="value">{{ selectedOrder.duration }}小时</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>费用信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">时长费率:</span>
              <span class="value">{{ selectedOrder.hourlyRate }}元/小时</span>
            </div>
            <div class="detail-item">
              <span class="label">总费用:</span>
              <span class="value cost">{{ selectedOrder.totalCost }}元</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section" v-if="selectedOrder.remark">
          <h4>备注信息</h4>
          <p>{{ selectedOrder.remark }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { useUserStore } from '../store/modules/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserOrders, updateOrderStatus } from '../api/order';
import { formatDateTime, formatBookingDate, formatRelativeTime, parseAndFormatTime } from '../utils/dateFormat';
import {
  Document,
  Clock,
  Check,
  Money,
  Search,
  Refresh,
  Close,
  CreditCard,
  VideoPlay,
  VideoPause,
  View,
  RefreshRight
} from '@element-plus/icons-vue';

export default {
  name: 'MyOrders',
  components: {
    Document,
    Clock,
    Check,
    Money,
    Search,
    Refresh,
    Close,
    CreditCard,
    VideoPlay,
    VideoPause,
    View,
    RefreshRight
  },
  setup() {
    const userStore = useUserStore();
    const detailDialogVisible = ref(false);
    const selectedOrder = ref(null);
    const activeTab = ref('active'); // 'active' 或 'history'

    // 筛选条件
    const filters = reactive({
      status: '',
      dateRange: [],
      search: ''
    });

    // 订单数据
    const orders = ref([]);
    const loading = ref(false);
    const selectedOrders = ref([]); // 选中的订单ID列表

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });

    // 过滤后的订单
    const filteredOrders = computed(() => {
      return orders.value.filter(order => {
        // 状态筛选
        if (filters.status && order.status !== filters.status) {
          return false;
        }

        // 日期范围筛选
        if (filters.dateRange && filters.dateRange.length === 2) {
          const orderDate = new Date(order.date);
          const startDate = new Date(filters.dateRange[0]);
          const endDate = new Date(filters.dateRange[1]);
          if (orderDate < startDate || orderDate > endDate) {
            return false;
          }
        }

        // 搜索筛选
        if (filters.search) {
          const keyword = filters.search.toLowerCase();
          return (
            order.id.toString().includes(keyword) ||
            order.tableName.toLowerCase().includes(keyword) ||
            order.tableType.toLowerCase().includes(keyword) ||
            order.phone.includes(keyword)
          );
        }

        return true;
      });
    });

    // 统计计算属性
    const totalOrdersCount = computed(() => orders.value.length);

    // 批量操作相关计算属性
    const selectedOrdersData = computed(() => {
      return orders.value.filter(order => selectedOrders.value.includes(order.id));
    });

    const pendingOrdersCount = computed(() => {
      return selectedOrdersData.value.filter(order => order.status === 'pending').length;
    });

    const cancelableOrdersCount = computed(() => {
      return selectedOrdersData.value.filter(order =>
        ['pending', 'confirmed'].includes(order.status)
      ).length;
    });

    const canBatchPay = computed(() => {
      return pendingOrdersCount.value > 0;
    });

    const canBatchCancel = computed(() => {
      return cancelableOrdersCount.value > 0;
    });

    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        pending: 'warning',
        confirmed: 'success',
        using: 'primary',
        completed: 'info',
        cancelled: 'danger'
      };
      return statusMap[status] || 'info';
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待支付',
        confirmed: '已支付',
        using: '使用中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[status] || '未知';
    };

    // 格式化创建时间
    const formatCreateTime = (dateTimeStr) => {
      return formatRelativeTime(dateTimeStr);
    };

    // 格式化预订日期
    const formatDate = (dateStr) => {
      return formatBookingDate(dateStr);
    };

    // 获取时间段文本
    const getTimeSlotText = (timeSlot) => {
      const timeSlotMap = {
        'slot_09': '09:00-10:00',
        'slot_10': '10:00-11:00',
        'slot_11': '11:00-12:00',
        'slot_12': '12:00-13:00',
        'slot_13': '13:00-14:00',
        'slot_14': '14:00-15:00',
        'slot_15': '15:00-16:00',
        'slot_16': '16:00-17:00',
        'slot_17': '17:00-18:00',
        'slot_18': '18:00-19:00',
        'slot_19': '19:00-20:00',
        'slot_20': '20:00-21:00',
        'slot_21': '21:00-22:00',
        // 兼容旧格式
        'morning1': '上午 09:00-11:00',
        'morning2': '上午 11:00-13:00',
        'afternoon1': '下午 13:00-15:00',
        'afternoon2': '下午 15:00-17:00',
        'afternoon3': '下午 17:00-19:00',
        'evening1': '晚上 19:00-21:00',
        'evening2': '晚上 21:00-23:00'
      };
      return timeSlotMap[timeSlot] || `${timeSlot}`;
    };

    // 加载订单数据
    const loadOrders = async () => {
      try {
        loading.value = true;
        const response = await getUserOrders({
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
          status: filters.status,
          search: filters.search
        });

        if (response.success) {
          // 转换字段名从下划线到驼峰格式
          const ordersList = response.data.items || response.data.orders || [];
          orders.value = ordersList.map(order => ({
            id: order.id,
            tableId: order.table_id,
            tableName: order.table_name,
            tableType: order.table_type,
            date: order.booking_date,
            timeSlot: `${order.start_time} - ${order.end_time}`,
            startTime: order.start_time,
            endTime: order.end_time,
            duration: order.duration,
            totalCost: parseFloat(order.total_cost || 0),
            hourlyRate: order.duration > 0 ? parseFloat(order.total_cost || 0) / order.duration : 0,
            phone: order.phone,
            remark: order.remark || '',
            status: order.status,
            createTime: order.created_at,
            updateTime: order.updated_at
          }));
          pagination.total = response.data.total || ordersList.length;
        } else {
          ElMessage.error('获取订单列表失败');
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        ElMessage.error('获取订单列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 搜索订单
    const searchOrders = () => {
      ElMessage.success('搜索完成');
    };

    // 重置筛选条件
    const resetFilters = () => {
      filters.status = '';
      filters.dateRange = [];
      filters.search = '';
      ElMessage.success('筛选条件已重置');
    };

    // 表格选择处理
    const handleSelectionChange = (selection) => {
      selectedOrders.value = selection.map(order => order.id);
    };

    // 清空选择
    const clearSelection = () => {
      selectedOrders.value = [];
    };

    // 批量支付订单
    const batchPayOrders = () => {
      const pendingOrders = selectedOrdersData.value.filter(order => order.status === 'pending');
      if (pendingOrders.length === 0) {
        ElMessage.warning('没有可支付的订单');
        return;
      }

      ElMessageBox.confirm(`确认支付选中的 ${pendingOrders.length} 个订单？`, '批量支付确认', {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        for (const order of pendingOrders) {
          await updateOrderStatusLocal(order.id, 'confirmed');
        }
        ElMessage.success(`批量支付成功！共支付了 ${pendingOrders.length} 个订单`);
        clearSelection();
      }).catch(() => {
        ElMessage.info('已取消批量支付');
      });
    };



    // 批量取消选中订单
    const batchCancelSelected = async () => {
      const cancelableOrders = selectedOrdersData.value.filter(order =>
        ['pending', 'confirmed'].includes(order.status)
      );

      if (cancelableOrders.length === 0) {
        ElMessage.warning('没有可取消的订单');
        return;
      }

      try {
        await ElMessageBox.confirm(
          `确认取消选中的 ${cancelableOrders.length} 个订单？此操作不可恢复。`,
          '批量取消订单',
          {
            confirmButtonText: '确认取消',
            cancelButtonText: '保留订单',
            type: 'warning'
          }
        );

        for (const order of cancelableOrders) {
          await updateOrderStatusLocal(order.id, 'cancelled');
        }

        ElMessage.success(`批量取消成功！共取消了 ${cancelableOrders.length} 个订单`);
        clearSelection();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量取消失败');
        }
      }
    };

    // 支付订单
    const payOrder = (order) => {
      ElMessageBox.confirm('确认支付此订单？', '支付确认', {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 更新订单状态为已支付
        await updateOrderStatusLocal(order.id, 'confirmed');
        ElMessage.success('支付成功！');
      }).catch(() => {
        ElMessage.info('已取消支付');
      });
    };

    // 取消订单
    const cancelOrderLocal = (order) => {
      ElMessageBox.confirm('确认取消此订单？取消后不可恢复。', '取消确认', {
        confirmButtonText: '确认取消',
        cancelButtonText: '保留订单',
        type: 'warning'
      }).then(async () => {
        await updateOrderStatusLocal(order.id, 'cancelled');
        ElMessage.success('订单已取消');
      }).catch(() => {
        ElMessage.info('已保留订单');
      });
    };

    // 开始使用
    const startUsing = async (order) => {
      await updateOrderStatusLocal(order.id, 'using');
      ElMessage.success('开始使用，祝您游戏愉快！');
    };

    // 结束使用
    const finishUsing = async (order) => {
      await updateOrderStatusLocal(order.id, 'completed');
      ElMessage.success('使用完成，感谢您的光临！');
    };

    // 查看订单详情
    const viewOrderDetail = (order) => {
      selectedOrder.value = order;
      detailDialogVisible.value = true;
    };

    // 再次预订
    const reorderOrder = (order) => {
      ElMessageBox.confirm(
        `确认重新预订 "${order.tableName}" 吗？`,
        '再次预订',
        {
          confirmButtonText: '确认预订',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(() => {
        // 跳转到预订页面，并传递台球桌信息
        this.$router.push({
          path: '/booking',
          query: {
            tableId: order.tableId,
            tableName: order.tableName,
            tableType: order.tableType
          }
        });
      }).catch(() => {
        // 用户取消
      });
    };

    // 更新订单状态
    const updateOrderStatusLocal = async (orderId, status) => {
      try {
        const response = await updateOrderStatus(orderId, { status });

        if (response && response.success) {
          // 重新加载订单列表以获取最新数据
          await loadOrders();
          return true;
        } else {
          ElMessage.error(response?.message || '订单状态更新失败');
          return false;
        }
      } catch (error) {
        console.error('订单状态更新失败:', error);
        ElMessage.error('订单状态更新失败');
        return false;
      }
    };

    onMounted(() => {
      loadOrders();
    });

    return {
      filters,
      orders,
      filteredOrders,
      loading,
      pagination,
      detailDialogVisible,
      selectedOrder,
      selectedOrders,
      selectedOrdersData,
      totalOrdersCount,
      pendingOrdersCount,
      cancelableOrdersCount,
      canBatchPay,
      canBatchCancel,
      getStatusType,
      getStatusText,
      formatCreateTime,
      formatDate,
      getTimeSlotText,
      loadOrders,
      resetFilters,
      handleSelectionChange,
      clearSelection,
      batchPayOrders,
      batchCancelSelected,
      payOrder,
      cancelOrderLocal,
      startUsing,
      finishUsing,
      reorderOrder,
      viewOrderDetail,
      updateOrderStatusLocal
    };
  }
};
</script>

<style scoped>
.my-orders-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.header-left p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 20px;
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-form {
  margin: 0;
}

.filter-form .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.filter-form .el-form-item:last-child {
  margin-right: 0;
}

/* 订单表格容器 */
.orders-table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 批量操作 */
.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f0f9ff;
  border-bottom: 1px solid #e5e7eb;
}

.batch-info {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
.orders-table {
  width: 100%;
}

.orders-table .el-table__header {
  background: #f9fafb;
}

.orders-table .el-table__header th {
  background: #f9fafb !important;
  color: #374151;
  font-weight: 600;
  border-bottom: 1px solid #e5e7eb;
}

.orders-table .el-table__row:hover {
  background: #f9fafb;
}

.order-id {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  color: #6b7280;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
}

.table-info {
  display: flex;
  flex-direction: column;
}

.table-name {
  font-weight: 500;
  color: #111827;
  font-size: 14px;
}

.table-type {
  font-size: 12px;
  color: #6b7280;
}

.time-info {
  display: flex;
  flex-direction: column;
}

.time-info .date {
  font-size: 12px;
  color: #6b7280;
}

.time-info .time {
  font-weight: 500;
  color: #111827;
  font-size: 14px;
}

.duration {
  font-weight: 600;
  color: #059669;
}

.cost {
  font-weight: 600;
  color: #dc2626;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 分页 */
.pagination-container {
  padding: 16px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #e5e7eb;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 订单详情对话框 */
.order-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  color: #333;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  font-size: 16px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item .label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.detail-item .value {
  color: #333;
  font-size: 14px;
}

.detail-item .value.cost {
  color: #f56c6c;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-orders-container {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    gap: 12px;
    padding: 16px;
  }

  .filter-form {
    flex-direction: column;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }

  .batch-actions {
    flex-direction: column;
    gap: 8px;
  }

  .action-buttons {
    justify-content: center;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }
}
</style>
